import React from 'react';
import { Routes, Route } from 'react-router-dom';
import { Layout, Alert } from 'antd';
import ProjectList from './pages/ProjectList';
import ProjectDetail from './pages/ProjectDetail';
import ExperimentResults from './pages/ExperimentResults';
import Login from './pages/Login';
import ProtectedRoute from './components/system/ProtectedRoute';
import { VisualizationProvider } from './contexts/VisualizationContext';
import './App.css';

const { Content } = Layout;

// 错误边界组件
class ErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { hasError: boolean; error?: Error }
> {
  constructor(props: { children: React.ReactNode }) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('React Error Boundary caught an error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ padding: '20px' }}>
          <Alert
            message="应用加载错误"
            description={
              <div>
                <p>React应用加载时发生错误：</p>
                <pre>{this.state.error?.message}</pre>
                <p>请检查控制台获取更多信息。</p>
              </div>
            }
            type="error"
            showIcon
          />
        </div>
      );
    }

    return this.props.children;
  }
}

const App: React.FC = () => {
  // 添加调试信息
  console.log('🚀 App组件开始渲染');
  console.log('环境信息:', {
    userAgent: navigator.userAgent,
    isElectron: navigator.userAgent.toLowerCase().indexOf('electron') > -1,
    location: window.location.href
  });

  return (
    <ErrorBoundary>
      <VisualizationProvider>
        <Routes>
          <Route path="/login" element={<Login />} />
          <Route
            path="/"
            element={
              <ProtectedRoute>
                <ProjectList />
              </ProtectedRoute>
            }
          />
          <Route
            path="/project/:projectId"
            element={
              <ProtectedRoute>
                <ProjectDetail />
              </ProtectedRoute>
            }
          />
          <Route
            path="/project/:projectId/experiments"
            element={
              <ProtectedRoute>
                <ExperimentResults />
              </ProtectedRoute>
            }
          />
        </Routes>
      </VisualizationProvider>
    </ErrorBoundary>
  );
};

export default App;
